package filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.JdbcUtil;
import util.Log;

public class CookieFilter implements Filter {
	Connection conn = null;
	public void destroy() {
		// TODO Auto-generated method stub
	}
	public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest req = ((HttpServletRequest) request);
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		Cookie[] cookies = req.getCookies();
		boolean saveLogin = false;
		boolean login = false;
		System.out.println("do filter: session username"+ session.getAttribute("username"));
		if (session.getAttribute("username") == null) {
			System.out.println("username null");
			if (cookies != null && cookies.length > 0) {
				// 如果没有用户的session，就到数据库检测，是否已登录
				String str = "(";
				for (int i = 0; i < cookies.length; i++) {
					System.out.println(cookies[i].getName()+"="+cookies[i].getValue());
					if (cookies[i].getName().length() == 32) {
						str +="'"+ cookies[i].getValue()+"',";
						if(cookies[i].getValue().startsWith("+")){//说明该用户选择了保存cookie
							saveLogin = true;
						}
					}
				}
				
				//如果网站保存了cookie 检测是否保存有用户登录过 的 cookie
				for (int i = 0; i < cookies.length; i++){
					if(cookies[i].getName().equals("login")){ //如果存在，就直接登录
						if(saveLogin){
							req.getSession().setAttribute("username", cookies[i].getValue());
						}
					}
				}
				 
				if(saveLogin && login){ //如果，有joomla的login cookie，并且有java的login cookie
					
				}else{
					str = str.substring(0, str.length() - 1);
					str += ")";
					
					System.out.println("sql:  "+str);
					if(str.length() > 1){ //防止sql语句错误
						PreparedStatement stm;
						try {
							stm = conn
									.prepareStatement("select username,session_id from joo_session where session_id in "
											+ str + " and guest=0");
							ResultSet set = stm.executeQuery();
							// 检测到该用户已在joomla登录。就保存cookie  保存session
							while (set.next()) {
								String username = set.getString(1);
								// System.out.println(name);
								req.getSession().setAttribute("username", username);

								// 生成cookie
								Cookie cookie = new Cookie("username", username);
								cookie.setPath("/");
								//cookie.setMaxAge(1800);
								res.addCookie(cookie);

								// Joomla 映射用户名的cookie
								Cookie cookie2 = new Cookie(username, set.getString(2));
								cookie2.setPath("/");
								//cookie.setMaxAge(1800);
								res.addCookie(cookie2);
								
								if(saveLogin){
									System.out.println("保存登录cookie");
									Cookie haslogin = new Cookie("haslogin", set.getString(1));
									haslogin.setPath("/");
									haslogin.setMaxAge(3600000);
									res.addCookie(haslogin);
								}
								break;
							}
						} catch (SQLException e) {
							Log.err2DB("检测seesion时出错", e,"SQL error", req);
							e.printStackTrace();
						}
					}
				}
			
			}
		}else{ //如果检测到已有该用户的session，还需检测，该用户是否已在 joomla 退出
			System.out.println("检测到session");
			
			//先找到，key为 username的cookie
			String username = (String) session.getAttribute("username");
			String session_id = null;
			int s_index = 0; //session_id所在cookie下标
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(username)) {//username - session_id
					session_id = cookies[i].getValue(); //得到session_id
					s_index = i;
				}
			}
			
			boolean online = false;
			//看看 该session_id还是否存在。 不存在说明用户已退出
			for (int i = 0; i < cookies.length; i++) {
				//说明该用户没有退出
				if (cookies[i].getValue().equals(session_id) && !cookies[i].getName().equals(username)) {
					online = true;
					System.out.println("用户依然在线");
				}
			}
			if(!online){
				session.setAttribute("username", null);
				System.out.println("用户已退出 销毁session");
			}
		}
		
		arg2.doFilter(request, response);
	}
	public void init(FilterConfig arg0) throws ServletException {
		conn = JdbcUtil.getConnection("joomla");
	}
}
